package com.uni.sofia.reader.utils
{
	import com.uni.sofia.reader.model.ApplicationManager;
	
	import mx.controls.Alert;
	
	import org.hamcrest.Matcher;

    /**
    * Utility class for parsing URLs and other staff
    */
	public class UrlParser
	{
		/**
		 * Parses the states strings from urls
		 * @param url
		 * 		url to be parsed to state string
		 * @return 
		 * 		the state string
		 * @see ApplicationManager
		 */
		public function parseState(url:String):String
		{
			return parseProperty(url, 'state');
		}
		
		/**
		 * Parses the specific property from the given url
		 * @param url
		 * 		url to be parsed
		 * @param property
		 * 		property to be get
		 * @return
		 * 		returns the concrete property
		 */ 
		public function parseProperty(url:String, property:String):String
		{
			if(url == null || url == "" || url == "#") return ApplicationManager.DEFAULT_STATE;
			
			var regExp:RegExp = new RegExp('#.*');
			var arr:Array = url.match(regExp);
			
			if(arr == null) return ApplicationManager.DEFAULT_STATE;
			
			var s:String = (arr[0] as String).substr(1);
			if(s.charAt(0) != "{" || s.charAt(s.length - 1) != "}")
				return ApplicationManager.DEFAULT_STATE;
			
			var arr1:Array = s.substr(1, s.length - 2).split("&");
			
			if(arr1 == null) return ApplicationManager.DEFAULT_STATE;
			
			var o:Object = {};
			for(var el:* in arr1)
			{
				var stru:String = arr1[el];
				o[parseFirst(stru)] = parseSecond(stru);
			}
			if(o[property] != null)
				return o[property];
			else 
				return ApplicationManager.DEFAULT_STATE;
		}
		
		/**
		 * From string like 'string1=string2'
		 * @param
		 * 		the string to be parsed
		 * @return
		 * 		the first, 'string1' in this concrete state
		 */ 
		public function parseFirst(s:String):String
		{
			var arr:Array = s.split('=');
			return arr[0] as String;
		}
		
		/**
		 * From string like 'string1=string2',
		 * @param
		 * 		the string to be parsed
		 * @return
		 * 		the second, 'string2' in this concrete state
		 */ 
		public function parseSecond(s:String):String
		{
			var arr:Array = s.split('=');
			return arr[1] as String;
		}
		
		/**
		 * From state property, url is build
		 * @state
		 * 		state from which the url must be build
		 * @return 
		 * 		the url
		 */ 
		public function stateToUrl(state:String):String
		{
			return "{state="+state+"}";	
		}
		
		/**
		 * Parser a action script object to URL
		 * @param json
		 * object to be parsed
		 * @return the url 
		 */ 
		public function jsonToUrl(json:Object):String
		{
			var str:String = '';
			for(var o:String in json)
			{
				str += o+'='+json[o]+'&';
			}
			return "#{"+str.substr(0, str.length-1)+"}";
		}
	}
}